﻿using System;
using System.IO;
using HtmlAgilityPack;

namespace dse_pe_parser
{
    internal class DailyPeRatiosProviderDsebd : IDailyPeRatiosProvider
    {
        private string _peListingHtml;

        #region Implementation of IDailyPeRatiosProvider

        public string Name
        {
            get { return "Dsebd.org P/E Ratios provider"; }
        }

        public float Version
        {
            get { return 0.01F; }
        }

        public void Prepare()
        {
            //TODO: Implement fetching of the pe ratio page from dsebd.org
            _peListingHtml = File.ReadAllText("pe.html").Trim();
        }

        public PeRatiosList Fetch()
        {
            var htmlDoc = new HtmlDocument {OptionFixNestedTags = true, OptionAutoCloseOnEnd = true};
            htmlDoc.LoadHtml(_peListingHtml);

            var peList = new PeRatiosList();

            if (htmlDoc.DocumentNode != null)
            {
                var tableNode = htmlDoc.DocumentNode.SelectSingleNode("//table");
                var date = extractDate(htmlDoc.DocumentNode.InnerHtml);

                if (tableNode != null)
                {
                    var rowNodes = tableNode.SelectNodes("//tr");
                    var skipFirstRow = true;

                    foreach (var rowNode in rowNodes)
                    {
                        if (skipFirstRow)
                        {
                            skipFirstRow = false;
                            continue;
                        }

                        parsePeTableRow(rowNode, date, peList);
                    }
                }
            }

            return peList;
        }

        /// <summary>
        /// Parses the date from HTML snippet
        /// </summary>
        private DateTime extractDate(string snippet)
        {
            return DateTime.Today;
        }

        /// <summary>
        /// Extracts P/E ratios from the table row
        /// </summary>
        private void parsePeTableRow(HtmlNode rowNode, DateTime date, PeRatiosList peList)
        {
            var childNodes = rowNode.ChildNodes;
            if (childNodes.Count >= 12)
            {
                decimal peLatest, peAudited;
                var symbol = childNodes[1].InnerText.Trim().ToUpperInvariant();
                decimal.TryParse(childNodes[3].InnerText.Trim(), out peLatest);
                decimal.TryParse(childNodes[9].InnerText.Trim(), out peAudited);

                // weed out invalid records
                if (!string.IsNullOrEmpty(symbol) && ((peAudited != 0m) || (peLatest != 0m)))
                {
                    peList.AddPeRatio(symbol, date, peLatest, peAudited);
                }
            }
        }

        #endregion
    }
}